angular.module('TagPrint')
    .controller('TagPrint.TagPrintCtrl', ['$scope', '$state', '$http', '$ionicLoading', 'Http', 'imanDialog', 'imanUsbPort', 'Device', '$ionicModal', '$cordovaToast', '$rootScope', 'TagPrintHomeService','User','DevicePort',
        function ($scope, $state, $http, $ionicLoading, Http, imanDialog, imanUsbPort, Device, $ionicModal, $cordovaToast, $rootScope,TagPrintHomeService,User,DevicePort) {
            $scope.data = {
                Barcode: '',//芯片id
                barcode: {},//芯片单品数据集合
                selectDevice: '',//存储蓝牙地址
                PrintConnect: '打印机未连接',//打印机是否连接
                flagPrintConnect: true,//打印机是否连接标志位
                pairedDevices: [],//已经配对的蓝牙
                selectClass: '',//选中的班次
                classes:[]//所有的班次
                
            };
            var flagRealData = false; //测试数据false 真实数据true
            if(User.get("_id")){
                var userId = User.get("_id");//用户id
            }
            
            
            var toast;

            var oneModel = '';
            var drawingRev = '';
            var oneClass = '';
            var oneCode = '';
            // var model = "CXGR280Y-1";//订单料号
            // var remarks = "CT1-D";//订单备注字段
            // var chipId = "1234567890"; //芯片id
            var dateTime = "16-07-15";//日期
            // var specification = "1";//尺寸 

            $ionicModal.fromTemplateUrl(u9ImHd.getFullPath('tpls/setting.html', 'TagPrint'), {
                scope: $scope,
                animation: 'slide-in-right'
            }).then(function (modal) {
                $scope.modal = modal;
            });
            $ionicModal.fromTemplateUrl(u9ImHd.getFullPath('tpls/settingClass.html', 'TagPrint'), {
                scope: $scope,
                animation: 'slide-in-right'
            }).then(function (modal) {
                $scope.modalClass = modal;
            });

            document.addEventListener('bluetoothprint.DataReceived', function (e) {
                $rootScope.$broadcast('bluetoothprint.DataReceived', e.bluetoothPrintData);
            }, false);
            document.addEventListener('bluetoothprint.StatusReceived', function (e) {
                $rootScope.$broadcast('bluetoothprint.StatusReceived', e.bluetoothPrintStatus);
            }, false);

            document.addEventListener("deviceready", function () {

                $scope.$on('bluetoothprint.DataReceived', function (e, data) {

                    $scope.data.pairedDevices = [];
                    var dataArray = data.split(",");
                    for (var i = 0; i < dataArray.length - 1; i++) {
                        var str = dataArray[i];
                        var name = str.substring(0, str.indexOf("&"));
                        var address = str.substring(str.indexOf("&") + 1);
                        $scope.data.pairedDevices.push({
                            name: name,
                            address: address
                        });
                    }

                    $scope.modal.show().then(function () {
                        // $scope.$apply();
                    });

                });

                $scope.$on('bluetoothprint.StatusReceived', function (e, data) {
                    
                    if (data === "true") {
                        if ($scope.data.selectDevice != null && $scope.data.selectDevice !== "") {
                            window.localStorage.setItem("gprinter", angular.toJson($scope.data.selectDevice));
                        }
                        $scope.data.PrintConnect = '打印机已连接';
                        $scope.data.flagPrintConnect = true;
                        // $cordovaToast.showShortBottom('连接成功');   
                    }
                    else if(data === "false"){

                    }
                    else{

                    }
                    $ionicLoading.hide();

                });

                //如果有打印机地址，连接打印机
                var gprinter_address = angular.fromJson(window.localStorage.getItem("gprinter")) + "";   
                if (gprinter_address != null && gprinter_address !== "") {
                    connectGPrint(gprinter_address);
                }

            }, false);
            //提交方法（添加或更新）
            function submitData(){
                    var deviceId = '';
                    var deviceName = '';
                    var workId = '';
                    var workName = '';
                    var WorkLocationId = '';
                    var WorkLocationName = '';

                    if(Device.get("Terminal")){
                        deviceId = Device.get("Terminal")._id;
                        deviceName = Device.get("Terminal").Name;
                    }
                    if(Device.get("Work")){
                        workId = Device.get("Work")._id;
                        workName = Device.get("Work").Name;
                    }
                    if(Device.get("WorkLocation")){
                        WorkLocationId = Device.get("WorkLocation")._id;
                        WorkLocationName = Device.get("WorkLocation").Name;
                    }
                    
                    if(flagRealData){
                        //更新数据
                        if( (deviceId=== $scope.data.barcode.Terminal) &&
                            (!$scope.data.barcode.Work || (workId === $scope.data.barcode.Work._id))
                        ){
                            imanDialog.showLoading();
                            TagPrintHomeService.updateTagPrint($scope.data.barcode,userId).then(function(data) {
                                imanDialog.hideLoading();
                                if (data) {
                                    imanDialog.toastBottom("更新成功");
                                } else {
                                    imanDialog.toastBottom("更新失败");
                                }
                                
                            }, function(res) {
                                imanDialog.hideLoading();
                            });
                        }
                        //添加数据
                        else{
                            imanDialog.showLoading();
                            TagPrintHomeService.submitTagPrint($scope.data.barcode,deviceId,deviceName,workId,workName,WorkLocationId,WorkLocationName,userId).then(function(data) {
                                imanDialog.hideLoading();
                                if (data) {
                                    imanDialog.toastBottom("提交成功");
                                } else {
                                    imanDialog.toastBottom("提交失败");
                                }
                                
                            }, function(res) {
                                imanDialog.hideLoading();
                            });
                        }
                        
                    }
            }
            

            //打印方法
            function printTag(){
               
                    if($scope.data.barcode.ItemMasterCode.length>0 && $scope.data.barcode.ItemMasterCode.indexOf("-")>=0){
                        oneModel = $scope.data.barcode.ItemMasterCode.substring(0,$scope.data.barcode.ItemMasterCode.indexOf("-"));//型号
                        oneCode = oneModel.substring(oneModel.length-1);
                    }
                    
                    // submitData();
                        
                    //1型号,2图纸版本,3班别,4代号,5芯片ID,6日期,7尺寸
                    var descSeg1 = "";
                    if($scope.data.barcode.DescSeg1==="F"){
                       descSeg1 = "";
                    }
                    else{
                       descSeg1 = $scope.data.barcode.DescSeg1;
                    }
                    
                    cordova.plugins.BluetoothPrint.printText(oneModel, 
                        $scope.data.barcode.MO.Remark, $scope.data.selectClass, oneCode, $scope.data.barcode.Barcode, dateTime, descSeg1, function (success) {
                        imanDialog.toastBottom(success);
                        submitData();
                        
                    }, function (error) {
                        imanDialog.toastBottom(error);
                        
                    }); 
                
                
                
            }
            //连接打印机蓝牙(蓝牙地址)
            function connectGPrint(address) {
                // alert(address);
                if (address != null && address !== "" && address !== "null") {
                    $ionicLoading.show({
                        template: 'Loading...'
                    });
                    if (window.cordova && cordova.plugins.BluetoothPrint) {

                        cordova.plugins.BluetoothPrint.connectDevice(address, function (success) {

                        }, function (error) {
                            $cordovaToast.showShortBottom(error);
                        });
                    }
                }


            }

            //关闭打印机连接
            function closeGPrintConnect() {
                if (window.cordova && cordova.plugins.BluetoothPrint) {
                    cordova.plugins.BluetoothPrint.closeConnect();
                }
            }

            //写入流水
            function writeBizRecord() {
                $ionicLoading.show();
                var realUser, realWorkLocation, realWorkLocationName;
                /**
                 * 判断是否是非独立称重
                 */
                if ($scope.data.barcode.Work === Device.get().Work._id) {
                    realUser = $scope.data.Users;
                    realWorkLocation = $scope.data.barcode.WorkLocation;
                    realWorkLocationName = $scope.data.barcode.WorkLocationName;

                    Http.post({
                        url: '/api/Wrapper/setWrapperTagPrint',
                        data: {
                            Parameter: {
                                Barcode: $scope.data.Barcode,
                                TerminalUniqueID: Device.getUUID(),
                                Work: Device.get().Work._id || 0,
                                WorkName: Device.get().Work.Name || '',
                                realWorkLocation: realWorkLocation || '',
                                realWorkLocationName: realWorkLocationName || '',
                                Users: realUser
                            }
                        }
                    }).then(function () {
                        $ionicLoading.hide();
                        imanDialog.toastCenter('打印成功');
                    })['finally'](function () {
                        $ionicLoading.hide();
                    });
                } else {
                    imanDialog.toastCenter('打印成功');
                }
            }
            

            function getOneTestData(){
                 flagRealData = false;
                 $scope.data.barcode = {
                    Barcode:"A9C978DB",
                    ItemMasterCode:"GR280Y-1-15001",
                    DescSeg1:"2",
                    DescSeg2:"5",
                    MOLotNumber:"FD020301",
                    MOCode:"2016071101",
                    MO:{
                       Remark : "CT2A" 
                    }
                    
                 };
                 
                 dateTime = "16-07-15";//日期
                 if($scope.data.flagPrintConnect){//打印机已连接后打印
                    printTag();
                 } 
                   
            }

            function getOneData(inputStr){
                
                TagPrintHomeService.getBarcodeData(inputStr).then(function(barcodedata) {
                     flagRealData = true;
                     $scope.data.barcode = barcodedata;
                     dateTime = $scope.data.barcode.CreatedOn.substring(2,10);//日期
                     if($scope.data.flagPrintConnect){//打印机已连接后打印
                        printTag();
                     } 
                }, function(error) {
                   imanDialog.hideLoading();
                });    
            }
            
            $scope.$on('$ionicView.beforeLeave', function () {
                // imanUsbPort.stop();
                if (toast) {
                    toast.hide();
                    toast = null;
                }
                closeGPrintConnect();
                DevicePort.close();
            });
            $scope.$on('$ionicView.afterEnter', function () {
                // imanUsbPort.start();
                DevicePort.open({
                    device: 0,
                    baudrate: 115200,
                    parseFn: true
                }).then(function () {
                    imanDialog.toastBottom("成功");
                }, function (err) {
                    imanDialog.toastBottom(err);
                });
                var selectClass = angular.fromJson(window.localStorage.getItem("selectClass"));
                if(selectClass){
                    $scope.data.selectClass = selectClass;
                }
            });
            $scope.$on('devicePort.DataReceived', function (e, barcode) {
                $scope.data.Barcode = barcode;
                // getQcInfo($scope.data.Barcode);
                getOneData(barcode);
            });
           

            $scope.showToast = function (styleMes) {
                if (toast) {
                    toast.hide();
                }
                toast = imanDialog.toast({
                    message: styleMes,
                    position: 'center',
                    duration: false,
                    backdropClickToClose: false,
                    hardwareBackButtonClose: false
                });
            };

            $scope.showToast('请扫描单品信息');

            $scope.hideToast = function () {
                if (toast) {
                    toast.hide();
                    toast = null;
                }
            };
            $scope.getClasses = function () {
                imanDialog.showLoading(); 
                TagPrintHomeService.getClasses("Group").then(function(data) {
                   imanDialog.hideLoading(); 
                   $scope.data.classes = data;
                   $scope.modalClass.show().then(function () {
                        // $scope.$apply();
                    });
                }, function(error) {
                   imanDialog.hideLoading();
                });    

            };
            $scope.getOneClass = function (item) {

                $scope.data.selectClass = item.Name;
                window.localStorage.setItem("selectClass", angular.toJson($scope.data.selectClass));
                $scope.modalClass.hide();

            };

            $scope.getOneDevice = function (address) {

                $scope.data.selectDevice = address;
                $scope.modal.hide();

            };

            //获取配对蓝牙列表
            $scope.getPairedDevices = function () {

                if (window.cordova && cordova.plugins.BluetoothPrint) {

                    cordova.plugins.BluetoothPrint.getPairedDevices(function () {

                    }, function () {
                    });
                }
            };
            
            //打印方法
            $scope.print = function () {
                printTag();
                // getOneData('0006475632');
                // getOneData('A9C978DB');
            };
            //连接蓝牙
            $scope.connect = function () {
                connectGPrint($scope.data.selectDevice);
            };

            $scope.getData = function () {
                getOneTestData();
            };
            
        }
    ]);
